//
//  ShopOrderViewController.m
//  jianpai
//
//  Created by yrapp on 16/1/14.
//  Copyright © 2016年 yrapp. All rights reserved.
//

#import "ShopOrderViewController.h"
#import "ShopAddressTableViewCell.h"

#import "ShopOrderPriceTableViewCell.h"
#import "ShopOrderFootView.h"
#import "expressTableViewCell.h"
//#import "AddressTableViewController.h"
//#import "MainWebViewViewController.h"
#import "ShopMessageTableViewCell.h"
//收货地址
#import "ShopAddressModel.h"
#import "ShopModel.h"
//orderSave
#import "OrderSaveModel.h"
//支付页面
#import "ShopPayViewController.h"

#import "CartDetailTableViewCell.h"

@interface ShopOrderViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)ShopOrderFootView *footView;
//收货地址
@property (nonatomic,strong)NSMutableArray *addressArray;
//订单
@property (nonatomic,strong)NSMutableArray *detailArray;
//返回订单号
@property (nonatomic,strong)NSMutableArray *orderArray;
//商品总价格
@property (nonatomic,strong)NSString *money_total;

@end

@implementation ShopOrderViewController


- (void)alphNAV {
    
   
}


- (void)viewWillAppear:(BOOL)animated {
    
    [self alphNAV];
    [self upDataAddress];
    [self updataDetail];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addTableView];
    [self addFootView];
    //数据解析
    [self upDataAddress];
    [self updataDetail];

    //通知监控键盘
    // 解决键盘遮挡问题
    //选择didShow是因为需要键盘的高度
    //选择willHide是因为视图frame重置需要优先于键盘消失，否则表现得不连贯
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWasShown:)
//                                                 name:UIKeyboardWillShowNotification
//                                               object:nil];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWasHide:)name:UIKeyboardWillHideNotification object:nil];
    // Do any additional setup after loading the view.
    
}





//添加tableView
- (void)addTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 50) style:(UITableViewStylePlain)];
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 20, 0);
    self.tableView.backgroundColor = [UIColor colorWithRed:237.0/255 green:242.0/255 blue:242.0/255 alpha:1];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //注册
    [self.tableView registerClass:[ShopAddressTableViewCell class] forCellReuseIdentifier:@"cell"];
    //商品详情
    [self.tableView registerClass:[CartDetailTableViewCell class] forCellReuseIdentifier:@"detail"];
    //商品价格
    [self.tableView registerClass:[ShopOrderPriceTableViewCell class] forCellReuseIdentifier:@"price"];
    //支付配送
    [self.tableView registerClass:[expressTableViewCell class] forCellReuseIdentifier:@"pay"];
    //订单留言
    [self.tableView registerClass:[ShopMessageTableViewCell class] forCellReuseIdentifier:@"message"];
}
//添加footView
- (void)addFootView {
    
    self.footView = [[ShopOrderFootView alloc] initWithFrame:CGRectMake(0, kHeight - 50, kWidth, 50)];
    [self.footView.subOrderButton addTarget:self action:@selector(subButton) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.footView];
    
    
}


#pragma mark --- 提交订单 ---
//提交订单按钮
- (void)subButton {
    
    
    NSString *uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    
    NSString *url = [KOrderSave stringByAppendingString:[NSString stringWithFormat:@"&uuid=%@",uuid]];

    
    NSLog(@"orderSave  %@",url);
    
    [LORequestManger GET:url success:^(id response) {
       //返回订单号
        NSDictionary *dic = (NSDictionary *)response;
        OrderSaveModel *model = [OrderSaveModel setUpDateDic:dic];
        [self.orderArray addObject:model];
        
        
        
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    //弹出选择支付方式
    self.hidesBottomBarWhenPushed = YES;
    ShopPayViewController *payVC = [[ShopPayViewController alloc] init];
    [self.navigationController pushViewController:payVC animated:YES];

    NSLog(@"提交订单");
}

#pragma mark --- 数据解析 ---
- (NSMutableArray *)addressArray {
    if (!_addressArray) {
        _addressArray = [NSMutableArray array];
    }
    return _addressArray;
}
- (NSMutableArray *)detailArray {
    if (!_detailArray) {
        _detailArray = [NSMutableArray array];
    }
    return _detailArray;
}
- (NSMutableArray *)orderArray {
    if (!_orderArray) {
        _orderArray = [NSMutableArray array];
    }
    return _orderArray;
    
    
}

//解析收货地址
- (void)upDataAddress {
    
    self.addressArray = nil;
    
    //NSString *uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    
    NSString *url = [KOrderAddress stringByAppendingString:[NSString stringWithFormat:@"&uuid=5f7fba50d937521e708bde16edb095e62e9f9e49"]];
    
    NSLog(@"收货地址 %@",url);
    [LORequestManger GET:url success:^(id response) {
       
        NSDictionary *dic = (NSDictionary *)response;
        
       
        NSArray *data = dic[@"data"];
        
        for (NSDictionary *address in data) {
            ShopAddressModel *model = [ShopAddressModel setUpdateDic:address];
            [self.addressArray addObject:model];
        }
        
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//订单商品详情
- (void)updataDetail {
    
    
   // NSString *uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    
    NSString *url = [KOrderTwo stringByAppendingString:[NSString stringWithFormat:@"&uuid=5f7fba50d937521e708bde16edb095e62e9f9e49"]];
    NSLog(@"订单商品详情 %@",url);
    
    [LORequestManger GET:url success:^(id response) {
       
        self.detailArray = nil;
        
        //订单详情
        NSArray *dic = (NSArray *)response[@"data"];
        
        //商品总价格
        self.money_total = (NSString *)response[@"money_total"];
        self.footView.priceLabel.text = [NSString stringWithFormat:@"  实付款 ¥%@",self.money_total];
        
        for (NSDictionary *item in dic) {
            
            ShopModel *model = [ShopModel setUpdateDic:item];
            [self.detailArray addObject:model];
        }
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}


#pragma mark --- tableView ---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.detailArray.count;
    }else if (section == 2){
        return 1;
    }else if (section == 3){
        return 1;
    }
    return 1;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ShopAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        if (self.addressArray.count == 0) {
            cell.noAddress.hidden = NO;
            cell.nameImage.hidden = YES;
            cell.phoneImage.hidden = YES;
            cell.noAddress.text = @"请选择收货地址以确保商品顺利到达";
        }else {
            cell.noAddress.hidden = YES;
            cell.nameImage.hidden = NO;
            cell.phoneImage.hidden = NO;
            ShopAddressModel *model = self.addressArray[0];
        
            [cell setModel:model];
            
        }
        cell.accessoryType = UITableViewCellStyleValue1;
        
        return cell;
    }else if (indexPath.section == 1) {
        
        CartDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detail" forIndexPath:indexPath];
        if (self.detailArray.count > 0) {
            
            ShopModel *model = self.detailArray[indexPath.row];
         
            [cell setModel:model];
        }
        
        return cell;
    }else if (indexPath.section == 2) {
        // 配送方式
        expressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pay" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellStyleValue1;
        return cell;
    }else if (indexPath.section == 3) {
        // 优惠券
        expressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pay" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellStyleValue1;
        cell.payAndExpress.text = @"优惠券";
        return cell;
        
    }else if (indexPath.section == 4) {
        ShopMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"message" forIndexPath:indexPath];
        cell.messageText.delegate = self;
        return cell;
        
        
    }else if (indexPath.section == 5) {
        
        ShopOrderPriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"price" forIndexPath:indexPath];
        cell.shopPriceLabel.text = [NSString stringWithFormat:@"¥ %@",self.money_total];
        return cell;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 1) {
        return 120;
    }else if (indexPath.section == 2){
        return 50;
    }else if (indexPath.section == 3) {
        return 50;
    }else if (indexPath.section == 4) {
        return 85;
    }
    return 90;
}

//订单确认 界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {//收货地址界面
        
//        AddressTableViewController *addressVC = [[AddressTableViewController alloc] init];
//        self.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:addressVC animated:YES];
        
        
    }else if (indexPath.section == 1){//商品详情
        
//        MainWebViewViewController *webVC = [[MainWebViewViewController alloc] init];
//        
//        ShopModel *model = self.detailArray[indexPath.row];
//        webVC.image = model.pic_s;
//        webVC.url = model.gourl;
//        self.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:webVC animated:YES];
    }else if (indexPath.section == 2) {//支付配送
        
        
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 11;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    return view;

}

//当编辑时 隐藏占位符
- (void)textViewDidChange:(UITextView *)textView {
    UILabel *placeLabel = (UILabel *)[self.tableView viewWithTag:999];
    if (textView.text.length > 0) {
        placeLabel.alpha = 0;
    }else {
        placeLabel.alpha = 1;
    }
}


////拖动 时回收键盘
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    if (self.tableView == scrollView) {
//        UITextView *textView = (UITextView *)[self.tableView viewWithTag:1000];
//        [textView endEditing:YES];
//    }
//}
//
//
//-(void)keyboardWasShown:(NSNotification*)notification
//{
//    //获取键盘高度
//    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];
//    CGFloat keyBoradHeight=[value CGRectValue].size.height;
//    //    NSNumber* animationTime=notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
//    //    double time=[animationTime doubleValue];
//    //获取被遮挡控件距离controller底部的距离
//    
//    NSLog(@" 键盘的    %f",self.view.frame.origin.y);
//    
//    float a=self.view.frame.origin.y+self.view.frame.size.height;
//    float b = self.view.frame.size.height-a;
//    if (b<keyBoradHeight)
//    {
//        //动画效果
//        [UIView animateWithDuration:0.5
//                         animations:^
//         {
//             //键盘被挡住了
//             CGRect viewCGrect=self.view.frame;
//             //视图应该上移所以是－
//             viewCGrect.origin.y=viewCGrect.origin.y-(keyBoradHeight-b) + 50;
//             [self.view setFrame:viewCGrect];
//             
//         } completion:nil];
//        
//    }
//    
//}
//
//-(void)keyboardWasHide:(NSNotification*)notification
//{
////    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];
////    CGFloat keyBoradHeight=[value CGRectValue].size.height;
////    
////    float a=self.view.frame.origin.y+self.view.frame.size.height;
////    float b = self.view.frame.size.height-a;
////    
//    CGRect viewCGrect=self.view.frame;
////    viewCGrect.origin.y=viewCGrect.origin.y+(keyBoradHeight-b);
//    
//    viewCGrect.origin.y = 0;
//    [self.view setFrame:viewCGrect];
//    
//    
//    
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
